<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/4/18
 * Time: 13:31
 */

namespace app\common\lib;

use app\common\cachemodel\Fortune;
use app\common\cachemodel\Goods;
use app\common\cachemodel\Orders as OrdersCacheModel;
use app\common\cachemodel\OrdersGoods;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\OrdersLib as OrdersLibCacheModel;
use app\common\cachemodel\ZhunleCourse;
use app\common\lib\exception\ApiException;
use app\common\model\Orders as OrdersModel;
use app\common\model\Recode;
use app\common\model\Rectification as RectificationModel;
use app\common\pay\Ali;
use app\common\pay\Weixin;
use app\common\pay\Jd;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;


/**
 * 订单拓展类库
 * Class Orders
 * @package app\common\lib
 */
class Orders
{

    /**
     *  * 统一三方下单入口
     * @param array $map
     * @param int $goods_type //1=>虚拟,2=>实体
     * @return array|bool
     * @throws \Exception
     */
    public function unifyPayOrder($map = [], $goods_type = 1)
    {
        $trade_type = $map['trade_type'];
        $pay_des = $map['pay_des'];
        $total_amount = $map['total_amount'];
        $order_id = $map['order_id'];
        $oid = isset($map['order_id']) ? $map['oid'] : 0;
        $openid = $map['openid'];
        $time = time();
        $callback_url = $map['callback_url'];
        $order_type = $map['order_type'];
        $arr = [
            'status' => false,
            'data' => []
        ];
        //        支付订单
        switch (true)
        {
            // 支付宝APP支付 支付类型为 APP
            case $trade_type == 1:
                $total_amount = ($total_amount);// 以元为单位的
                $AliPay = new Ali();
                $pay_url = $AliPay->pay($pay_des, $order_id, $total_amount, 'APP', '', $goods_type);
                $arr = [
                    'status' => true,
                    'data' => [
                        'pay_url' => $pay_url,
                        'order_id' => $order_id,
                        'oid' => $oid
                    ],
                ];
                break;
            // 微信支付 2 APP支付  6 JSAPI支付 8 H5
            case in_array($trade_type, [2, 6, 8]):
                $total_amount = sprintf("%u", bcmul($total_amount, 100));// 以分为单位的
                $WxPay = new Weixin();
                // 获取支付类型 APP、JSAPI 或 H5
                //获取订单支付账号配置
                $accountConfig = OrdersLib::getOrderAccountType($order_id, 2);
                $wxpayConfig = self::getPayConfig('wx', $accountConfig['account']);

                if (empty($wxpayConfig))
                {
                    return $arr;
                }

                $wxPayType = $wxpayConfig['wx_pay_type'][$trade_type];
                // 获取微信配置信息
                $wxConfig = $wxpayConfig[$wxPayType['configName']];

                $data = $WxPay->pay($pay_des, $order_id, $total_amount, $wxPayType['type'], $wxConfig, $openid, $goods_type);
                // 下单成功
                if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS')
                {
                    switch ($trade_type)
                    {
                        // APP支付
                        case 2:
                            $sign['appid'] = $wxConfig['appid'];
                            $sign['partnerid'] = $wxConfig['mchid'];
                            $sign['prepayid'] = $data['prepay_id'];
                            $sign['package'] = 'Sign=WXPay';
                            $sign['noncestr'] = $WxPay->getRandChar(32);
                            $sign['timestamp'] = $time;
                            $sign['sign'] = $WxPay->getSign($sign, $wxConfig);
                            $sign['order_id'] = $order_id;
                            $sign['oid'] = $oid;

                            $data['nonce_str'] = $sign['noncestr'];
                            $data['sign'] = $sign['sign'];

                            $arr = [
                                'status' => true,
                                'data' => $sign,
                            ];
                            break;
                        // JSAPI支付
                        case 6:
                            $sign = [
                                'appId' => $wxConfig['appid'],
                                'timeStamp' => $time,
                                'nonceStr' => $WxPay->getRandChar(32),
                                'package' => 'prepay_id=' . $data['prepay_id'],
                                'signType' => 'MD5',
                            ];
                            $sign['paySign'] = $WxPay->getSignOfJsApi($sign, $wxConfig);

                            $sign['order_id'] = $order_id;
                            $sign['oid'] = $oid;
                            $arr = [
                                'status' => true,
                                'data' => $sign,
                            ];
                            break;
                        // H5支付返回
                        case 8:
                            $sign = [
                                'mweb_url' => ($data['mweb_url'] . '&redirect_url=' . ($order_type == 1 ? $callback_url : urlencode(urldecode($callback_url) . $order_id))),
                                'order_id' => $order_id,
                                'oid' => $oid
                            ];

                            $arr = [
                                'status' => true,
                                'data' => $sign,
                            ];
                            break;
                        default:
                            break;
                    }
                } else
                {
                    $ret = [
                        'return_code' => $data['return_code'],
                        'return_msg' => $data['return_msg'],
                    ];
                    $arr = [
                        'status' => false,
                        'data' => $ret,
                    ];
                }
                break;
            // 京东支付
            case $trade_type == 5:
//                $total_amount = sprintf("%u", $total_amount * 100);// 以分为单位的
//                $JdPay = new Jd();
//                $data = $JdPay->pay($pay_des, $order_id, $total_amount,$goods_type);
//                if ($data === false)
//                {
//                    $arr = [
//                        'status' => false,
//                        'data' => $data
//                    ];
//                } else
//                {
//                    $arr = [
//                        'status' => true,
//                        'data' => $data
//                    ];
//                }


                $data = [
                    'order_id' => $order_id,
                    'oid' => $oid,
                    'return_code' => 0,
                    'return_msg' => '京东支付支付错误，非常抱歉！',
                ];
                $arr = [
                    'status' => false,
                    'data' => $data
                ];

                break;
            // 支付宝手机网页支付 支付类型为 WAP
            case $trade_type == 7:
                $total_amount = ($total_amount);// 以元为单位的
                $AliPay = new Ali();
                $payForm = $AliPay->pay($pay_des, $order_id, $total_amount, 'WAP', $order_type == 1 ? $callback_url : urlencode(urldecode($callback_url) . $order_id), $goods_type);
                $arr = [
                    'status' => true,
                    'data' => [
                        'par_form' => $payForm,
                        'order_id' => $order_id,
                        'oid' => $oid,
                    ],
                ];
                break;
            case $trade_type == 9:
                $arr = [
                    'status' => true,
                    'data' => [
                        'order_id' => $order_id,
                        'oid' => $oid
                    ],
                ];
                break;
            default :
                return false;
        }

        return $arr;
    }

    /**
     * 检验订单支付状态
     * @throws \Exception
     */
    public function CheckOrder($uid, $rids, $gids, $order_type)
    {
        //检验是否有已支付订单和未支付订单
        $OrdersCacheModel = new OrdersCacheModel();
        $recodes = (new \app\common\cachemodel\Recode())->batchGetInfoByIds($rids);
        $rname = [];
        $res = true;
        $key_name = '';
        switch (true)
        {
            case $order_type == 1:
                $key_name = 'rectification_data';
                break;
            case in_array($order_type, [2, 3, 4]):
                $key_name = 'fortune_data';
                break;
            case $order_type == 5:
                $key_name = 'acgmap_data';
                break;
            case $order_type == 6:
                $key_name = 'video_data';
                break;
            case $order_type == 7:
                $key_name = 'data';
                break;
        }
        foreach ($rids as $rid)
        {
            $prepaids = $OrdersCacheModel->PrepaidUnpaidOrder($uid, $rid, $order_type, 1);
            if ($prepaids)
            {
                foreach ($prepaids as $prepaid)
                {
                    foreach ($prepaid[$key_name] as $item)
                    {
                        if (in_array($item['gid'], $gids))
                        {
                            $rname[] = $recodes[$rid];
                            $res = false;
                        }
                    }
                }
            }
        }
        if ($res === true)
        {
            foreach ($rids as $rid)
            {
                $prepaids = $OrdersCacheModel->PrepaidUnpaidOrder($uid, $rid, $order_type, 0);
                if ($prepaids)
                {
                    foreach ($prepaids as $prepaid)
                    {
                        foreach ($prepaid[$key_name] as $item)
                        {
                            if (in_array($item['gid'], $gids))
                            {
                                $OrdersCacheModel->DelData($prepaid['order_id'], ['is_del' => 1]);
                            }
                        }
                    }
                }
            }
        }
        return $res;
    }

    /**
     * 三方平台验证订单是否已经支付，并修改订单状态
     * @param $order_id
     * @return bool|string
     * @throws ApiException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws \Exception
     */
    public function validateOrders($order_id)
    {
        //获取当前订单信息
        $OrdersModel = new OrdersCacheModel();
        $order = $OrdersModel->getInfoById($order_id);
        if (!empty($order))
        {
            // 若该订单已支付，则直接返回已支付
            if (in_array($order['status'], [1, 4]))
            {
                if ($order['trade_type'] == 1)
                {
                    return '订单已在支付宝支付';
                }
                if ($order['trade_type'] == 2)
                {
                    return '订单已在微信支付';
                }
                return '订单已支付';
            }

            $orderAccount = isset($order['account']) ? (int)($order['account']) : 1;
            //查询支付宝平台该订单支付状态
            $ali = new Ali();
            $response = json_decode(json_encode($ali->query(['out_trade_no' => $order['order_id']], $orderAccount)), true);
            // 支付宝已经内置验签 支付成功
            if ($response['alipay_trade_query_response']['code'] == '10000')
            {
                $tarde_status = $response['alipay_trade_query_response']['trade_status'];
                //支付宝平台订单状态为已支付
                if ($tarde_status == 'TRADE_SUCCESS')
                {
                    //app订单状态为未支付
                    if (!in_array($order['status'], [1, 4]))
                    {
//                        //更新生时矫正订单状态并重新入队
//                        if (isset($order['reid']) && $order['reid'] > 0)
//                        {
//                            $status = $this->updateAndPushRedis(['uid' => $order['uid'], 'oid' => $order['id'], 'order_id' => $order['order_id'], 'id' => $order['reid']]);
//                        } //更新运势订单状态并重新入队
//                        elseif (isset($order['fid']) && (int)($order['fid']) > 0)
//                        {
//                            $status = $this->updateAndPushFortune(['fid' => $order['fid'], 'uid' => $order['uid'], 'oid' => $order['id'], 'update' => true]);
//                        }
                        //修改订单状态
                        $status = $this->updateOrders($order);
                        if ($status === false)
                        {
                            return '操作失败,请稍后重试';
                        }
                        // 订单状态成功修改后,删除订单缓存
                        (new OrdersModel())->rm_cache(['oid' => $order['id'], 'del_add' => 0, 'order_id' => $order['order_id'], 'uid' => $order['uid']]);
                    }
                    return '订单已在支付宝支付';
                }
            }
            //查询微信平台该订单支付状态
            $wxpayConfig = self::getPayConfig('wx', $orderAccount);
            if (empty($wxpayConfig))
            {
                return '操作失败,请稍后重试';
            }
            //获取微信支付类型
            $wxKey = array_keys($wxpayConfig['wx_pay_type']);
            //判断此订单在不同微信支付下是否已经支付
            foreach ($wxKey as $item)
            {
                $wxPayType = $wxpayConfig['wx_pay_type'][$item];
                // 获取微信配置信息
                $wxConfig = $wxpayConfig[$wxPayType['configName']];
                $res = $this->validateWxOrder($order, $wxConfig);
                if ($res !== true)
                {
                    return $res;
                }
            }
            // TODO  订单支付方式为京东支付
            if ($order['status'] == 2)
            {
                return '订单已关闭';
            }
        }
        return true;
    }


    /**
     * 验证微信平台订单支付状态
     * @param $order
     * @param $wxConfig
     * @return bool|string
     */
    public function validateWxOrder($order, $wxConfig)
    {
        $weixin = new Weixin();
        $response = $weixin->query($order['order_id'], $wxConfig);
        // 验签
        if ((new PayCheckSign())->weixin($response, $wxConfig['api_key']))
        {
            if ($response['return_code'] === 'SUCCESS')
            {
                //微信平台订单状态为已支付
                if ($response['result_code'] === 'SUCCESS' && $response['trade_state'] == 'SUCCESS')
                {
                    //app订单状态为未支付
                    if (!in_array($order['status'], [1, 4]))
                    {
                        //更新生时矫正订单状态并重新入队
//                            if (isset($order['reid']) && $order['reid'] > 0)
//                            {
//                                $status = $this->updateAndPushRedis(['uid' => $order['uid'], 'id' => $order['reid'], 'oid' => $order['id'], 'order_id' => $order['order_id']]);
//                            } //更新运势订单状态并重新入队
//                             elseif (isset($order['fid']) && (int)($order['fid']) > 0)
//                            {
//                                $status = $this->updateAndPushFortune(['fid' => $order['fid'], 'uid' => $order['uid'], 'oid' => $order['id'], 'update' => true]);
//                            }
                        $status = $this->updateOrders($order);
                        if ($status !== true)
                        {
                            return '操作失败,请稍后重试';
                        }
                        // 订单状态成功修改后,删除订单缓存
                        (new OrdersModel())->rm_cache(['oid' => $order['id'], 'del_add' => 0, 'order_id' => $order['order_id'], 'uid' => $order['uid']]);
                    }
                    return '订单已在微信支付';
                }
            } else
            {
                return '网络异常';
            }
        } else
        {
            return '网络异常';
        }
        return true;
    }

    /**
     * 更新订单状态为支付成功并添加任务到队列
     * @param array $map
     * @param bool $update
     * @return bool|string
     * @throws ApiException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    protected function updateAndPushRedis($map = [], $update = true)
    {
        $reid = $map['id'];
        $oid = $map['oid'];
        $order_id = $map['order_id'];

        //更新订单状态
        (new OrdersCacheModel())->UpdateData($order_id, ['status' => 1, 'pay_time' => time()], 1);

        //生时矫正入队
        $RecodeModel = new Recode();
        $rectification = RectificationModel::get(['id' => $reid]);

        $event_array = $rectification->events()->select();

        $recode = $RecodeModel->getRecode(['id' => $rectification['rid']]);

        $data = [
            'oid' => $oid,
            'order_id' => $order_id,
            'reid' => $reid,
            'start_time' => $rectification['start_time'],
            'end_time' => $rectification['end_time'],
            'events' => $event_array,
            'recode' => $recode
        ];
        $queueConfig = config('queue');
        queuePush($queueConfig['rectification_task'], $data, $queueConfig['rectification_queue'], $queueConfig['rectification_delay']);

        return true;
    }

    /**
     * 更新订单状态为支付成功并添加任务到队列
     * @param array $map
     * @return bool
     * @throws ApiException
     */
    protected function updateAndPushFortune($map = [])
    {
        return (new PushQueue())->Fortune(['uid' => $map['uid'], 'oid' => $map['oid']]);

//        $uid = $map['uid'];
//        $oid = $map['oid'];
//
//        $where = ['o.id' => $oid, 'o.gid' => ['in', config('goods.month_year_id')]];
//
//        try
//        {
//            $fortune = (new OrdersModel())
//                ->alias('o')
//                ->field('f.time,f.type,f.rids,g.expire_time,o.status,o.order_id')
//                ->join('wechat_backup_07_18_14_43_00.app_goods g', 'o.gid=g.id', 'INNER')
//                ->join('wechat_backup_07_18_14_43_00.app_fortune f', 'o.fid=f.id', 'INNER')
//                ->where($where)
//                ->findOrFail()->toArray();
//            (new OrdersCacheModel())->UpdateData($fortune['order_id'], ['status' => 1, 'pay_time' => time()], 1);
//        }
//        catch (\Exception $e)
//        {
//            $fortune = [];
//        }
//
//        if ($fortune && !empty($fortune))
//        {
//            $rids = explode(',', $fortune['rids']);
//
//            $start_time = $fortune['time'];
//            $end_time = strtotime($fortune['expire_time'], $fortune['time']);
//
//            $recode_info = [];
//            foreach ($rids as $rid)
//            {
//                //获取档案信息
//                $recode_info[] = (new Recode())->getRecode(['uid' => $uid, 'id' => $rid]);
//            }
//            switch ($fortune['type'])
//            {
//                case 2:
//                    $start_time = date('Y-m', $start_time);
//                    $end_time = date('Y-m', strtotime('-1 months', $end_time));
//                    break;
//                case 3:
//                    $start_time = date('Y', $start_time);
//                    $end_time = date('Y', strtotime('-1 years', $end_time));
//                    break;
//                default:
//                    $start_time = "";
//                    $end_time = "";
//            }
//            $unlock_time = prDates(['start' => $start_time, 'end' => $end_time, 'type' => $fortune['type']]);
//            //将运势加入队列运算
//            fortune_redis_job(['oid' => $oid, 'order_id' => $fortune['order_id'], 'recode_info' => $recode_info, 'unlock_time' => $unlock_time, 'ostatus' => $fortune['status'], 'ftype' => $fortune['type']]);
//        }

//        return true;
    }

    /**
     * 更新订单状态为支付成功
     * @param array $orders
     * @return bool|string
     */
    protected function updateOrders($orders)
    {
        // 更新数据库状态
        try
        {
            //订单状态
            $status = OrdersLibCacheModel::getOrderStatus([$orders['gid']], $orders['order_type']);
            (new OrdersCacheModel())->UpdateData($orders['order_id'], ['status' => $status, 'pay_time' => time()], 1);
        }
        catch (\Exception $e)
        {
            return false;
        }

        return true;
    }

    /**
     * 获取支付参数
     * 未获取到相关配置时，返回空数组
     * @param string $type 支付类型 ali=>支付宝 wx=>微信支付 jd=>京东支付
     * @param int $account 需要强制获取非使用中的配置，目前主要用于进行订单查询 （下单时不需要传参）
     * @return array
     */
    public static function getPayConfig($type = 'ali', $account = 0)
    {
        $type = strtolower($type) . 'pay';

        $config = config($type);

        if (empty($config))
        {
            return [];
        }

        if ($account > 0 && isset($config['account' . $account]))
        {
            $data = $config['account' . $account];
        } else
        {
            $data = $config['account' . $config['default']];
        }

        return $data;
    }

    /**
     * 获取订单详情
     * @param $orders
     * @return array
     * @throws \Exception
     */
    public function getOrderDetails($orders)
    {
        $arr = [];
        $reids = [];
        $fids = [];
        $oids = [];
        $video_gids = [];
        //订单区分类型
        if ($orders)
        {
            foreach ($orders as $order)
            {
                switch (true)
                {
                    case $order['order_type'] == 1:
                        $reids[] = $order['reid'];
                        break;
                    case in_array($order['order_type'], [2, 3, 4, 12]):
                        $fids[] = $order['fid'];
                        break;
                    case  in_array($order['order_type'], [5, 7, 13]):
                        $oids[] = $order['id'];
                        break;
                    case $order['order_type'] == 6:
                        $video_gids[] = $order['gid'];
                        break;
                }
            }
            //获取校准生辰详情
            if ($reids)
            {
                $recs = (new \app\common\cachemodel\Rectification())->getRecDetail($reids);
                $rec_rids = [];
                foreach ($recs as $rec)
                {
                    $rec_rids[] = $rec['rid'];
                }
                $recs_data = $this->OrderRecode($recs, $rec_rids);
            } else
            {
                $recs_data = [];
            }
            //获取运势详情
            if ($fids)
            {
                $fortunes = (new Fortune())->batchGetInfo($fids, ['id', 'type', 'time', 'rids', 'extend']);
                foreach ($fortunes as $k => $fortune)
                {
                    $rids = explode(',', $fortune['rids']);
                    $fortune_recodes = (new \app\common\cachemodel\Recode())->batchGetInfoByIds($rids, ['id', 'name', 'year', 'month', 'day']);
                    foreach ($fortune_recodes as $fortune_recode)
                    {
                        $fortunes[$k]['recode'][] = $fortune_recode;
                    }
                }
            } else
            {
                $fortunes = [];
            }
            $order_goods_data = [];
            //获取幸运之城详情和本命预测详情
            if ($oids)
            {
                $order_goods = (new OrdersGoods())->batchGetInfo($oids) ?: [];
                $order_rids = [];
                foreach ($order_goods as $order_good)
                {
                    foreach ($order_good as $k => $item)
                    {
                        $order_good[$k] = $og = json_decode($item, true);
                        $order_rids[] = $og['rid'];
                    }
                    $order_goods_data[$og['oid']] = $this->OrderRecode($order_good, $order_rids);
                }
            }
            //获取教学视频详情
            if ($video_gids)
            {
                $videos = (new ZhunleCourse())->batchGetInfoByGIds($video_gids);
            } else
            {
                $videos = [];
            }

            $GoodsCacheModel = new Goods();
            //获取校准生辰商品
            if ($recs_data)
            {
                $rec_goods = $GoodsCacheModel->GoodsTypeInfo(1);
            } else
            {
                $rec_goods = [];
            }
            //获取运势商品
            if ($fortunes)
            {
                $day_fortune_goods = $GoodsCacheModel->GoodsTypeInfo(2);
                $month_fortune_goods = $GoodsCacheModel->GoodsTypeInfo(3);
                $year_fortune_goods = $GoodsCacheModel->GoodsTypeInfo(4);
                $sim_month_fortune_goods = $GoodsCacheModel->GoodsTypeInfo(12);
            }
            //获取幸运之城商品和本命预测商品
            if ($order_goods_data)
            {
                $map_goods = $GoodsCacheModel->GoodsTypeInfo(5);
                $natal_report_goods = $GoodsCacheModel->GoodsTypeInfo(7);
                $sim_natal_report_goods = $GoodsCacheModel->GoodsTypeInfo(13);
            }
            //获取教学视频商品
            if ($videos)
            {
                $video_goods = $GoodsCacheModel->GoodsTypeInfo(6);
            }
            foreach ($orders as $order)
            {
                //新版订单状态统一，已完成为4,只有日运
                if (in_array($order['order_type'], [2, 6]) && $order['status'] == 4)
                {
                    $order_status = 1;
                } else
                {
                    $order_status = $order['status'];
                }
                $arr[$order['id']] = [
                    'uid' => (int)$order['uid'],
                    'oid' => (int)$order['id'],
                    'reid' => (int)$order['reid'],
                    'fid' => (int)$order['fid'],
                    'gid' => (int)$order['gid'],
                    'status' => (int)$order_status,
                    'trade_type' => (int)$order['trade_type'],
                    'total_price' => sprintf('%.2f', $order['total_amount']),
                    'create_time' => date('Y-m-d H:i:s', $order['create_time']),
                    'pay_time' => $order['pay_time'] ? date('Y-m-d H:i:s', $order['pay_time']) : 0,
                    'order_id' => $order['order_id'],
                    'order_type' => (int)$order['order_type'],
                    'extend' => $order['extend'],
                ];
                switch (true)
                {
                    case $recs_data && $order['order_type'] == 1:
                        $arr[$order['id']]['type'] = 1;
                        $arr[$order['id']]['order_name'] = '校准生辰';
                        $num = 1;
                        $arr[$order['id']]['rectification_data'] = [];
                        foreach ($recs_data as $rec_data)
                        {
                            if ($rec_data['id'] == $order['reid'])
                            {
                                foreach ($rec_goods as $rec_good)
                                {
                                    if ($rec_good['id'] == $order['gid'])
                                    {
                                        $rec_now_price = $rec_good['now_prize'];
                                        $rec_or_price = $rec_good['or_prize'];
                                        $activeDiscount = active($rec_good['id']);
                                        if ($activeDiscount['discount'])
                                        {
                                            $rec_now_price *= $activeDiscount['discount'];
                                        }
                                    }
                                }
                                $arr[$order['id']]['status'] = (int)$rec_data['status'];
                                $arr[$order['id']]['rectification_data'][] = [
                                    'rid' => (int)$rec_data['recode']['id'],
                                    'reid' => (int)$rec_data['id'],
                                    'gid' => 1,
                                    'rname' => $rec_data['recode']['name'],
                                    'birth' => Util::is_strtotime($rec_data['start_time']) == false ? date('Y-m-d', strtotime($rec_data['start_time'])) : date('Y-m-d', $rec_data['start_time']),
                                    'start_time' => date('H:i', $rec_data['start_time']),
                                    'end_time' => date('H:i', $rec_data['end_time']),
                                    'or_price' => $rec_or_price,
                                    'now_price' => $rec_now_price
                                ];
                            }
                        }
                        $arr[$order['id']]['count'] = $num;
                        $arr[$order['id']]['or_total_price'] = sprintf('%.2f', $rec_or_price * $num);
                        break;
                    case $fortunes && in_array($order['order_type'], [2, 3, 4, 12]):
                        $arr[$order['id']]['type'] = 2;
                        $arr[$order['id']]['order_name'] = '解锁运势';
                        $num = 0;
                        $arr[$order['id']]['fortune_data'] = [];
                        foreach ($fortunes as $fortune)
                        {
                            if ($fortune['id'] == $order['fid'])
                            {
                                switch (true)
                                {
                                    case $order['order_type'] == 2:
                                        $start_time = date('Y-m-d', $fortune['time']);
                                        foreach ($day_fortune_goods as $day_fortune_good)
                                        {
                                            if ($day_fortune_good['id'] == $order['gid'])
                                            {
                                                $fortune_now_price = $day_fortune_good['now_prize'];
                                                $fortune_or_price = $day_fortune_good['or_prize'];
                                                $end_time = date('Y-m-d', strtotime($day_fortune_good['expire_time'], $fortune['time']) - 86400);
                                                $activeDiscount = active($day_fortune_good['id']);
                                                if ($activeDiscount['discount'])
                                                {
                                                    $fortune_now_price *= $activeDiscount['discount'];
                                                }
                                            }
                                        }
                                        break;
                                    case $order['order_type'] == 3:
                                        $start_time = date('Y-m', $fortune['time']);
                                        foreach ($month_fortune_goods as $month_fortune_good)
                                        {
                                            if ($month_fortune_good['id'] == $order['gid'])
                                            {
                                                $fortune_now_price = $month_fortune_good['now_prize'];
                                                $fortune_or_price = $month_fortune_good['or_prize'];
                                                $end_time = date('Y-m', strtotime($month_fortune_good['expire_time'], $fortune['time']) - 86400);
                                                $activeDiscount = active($month_fortune_good['id']);
                                                if ($activeDiscount['discount'])
                                                {
                                                    $fortune_now_price *= $activeDiscount['discount'];
                                                }
                                            }
                                        }
                                        break;
                                    case $order['order_type'] == 4:
                                        $start_time = date('Y', $fortune['time']);
                                        foreach ($year_fortune_goods as $year_fortune_good)
                                        {
                                            if ($year_fortune_good['id'] == $order['gid'])
                                            {
                                                $fortune_now_price = $year_fortune_good['now_prize'];
                                                $fortune_or_price = $year_fortune_good['or_prize'];
                                                $end_time = date('Y', strtotime($year_fortune_good['expire_time'], $fortune['time']) - 86400);
                                                $activeDiscount = active($year_fortune_good['id']);
                                                if ($activeDiscount['discount'])
                                                {
                                                    $fortune_now_price *= $activeDiscount['discount'];
                                                }
                                            }
                                        }
                                        break;
                                    case $order['order_type'] == 12:
                                        $start_time = date('Y-m', $fortune['time']);
                                        foreach ($sim_month_fortune_goods as $month_fortune_good)
                                        {
                                            if ($month_fortune_good['id'] == $order['gid'])
                                            {
                                                $fortune_now_price = $month_fortune_good['now_prize'];
                                                $fortune_or_price = $month_fortune_good['or_prize'];
                                                $end_time = date('Y-m', strtotime($month_fortune_good['expire_time'], $fortune['time']) - 86400);
                                                $activeDiscount = active($month_fortune_good['id']);
                                                if ($activeDiscount['discount'])
                                                {
                                                    $fortune_now_price *= $activeDiscount['discount'];
                                                }
                                            }
                                        }
                                        break;
                                }
                                foreach ($fortune['recode'] as $frecode)
                                {
                                    $num += 1;
                                    $arr[$order['id']]['fortune_data'][] = [
                                        'id' => (int)$fortune['id'],
                                        'gid' => (int)$order['gid'],
                                        'rid' => $frecode['id'],
                                        'rname' => $frecode['name'],
                                        'fortune_type' => (int)$order['order_type'] - 1,
                                        'start_time' => $start_time,
                                        'end_time' => $end_time,
                                        'or_price' => $fortune_or_price,
                                        'now_price' => $fortune_now_price
                                    ];
                                }
                            }
                        }
                        $arr[$order['id']]['count'] = $num;
                        $arr[$order['id']]['or_total_price'] = sprintf('%.2f', $fortune_or_price * $num);
                        break;
                    case $order_goods_data && in_array($order['order_type'], [5, 7, 13]):
                        $num = 0;
                        $or_total_price = 0;
                        foreach ($order_goods_data as $ogk => $order_goods_datum)
                        {
                            if ($order['id'] == $ogk)
                            {
                                switch (true)
                                {
                                    case $order['order_type'] == 5:
                                        $arr[$order['id']]['acgmap_data'] = [];
                                        $arr[$order['id']]['order_name'] = '幸运之城';
                                        $arr[$order['id']]['type'] = 3;
                                        foreach ($map_goods as $map_good)
                                        {
                                            foreach ($order_goods_datum as $ogd)
                                            {
                                                if ($ogd['gid'] == $map_good['id'])
                                                {
                                                    $num += 1;
                                                    $arr[$order['id']]['acgmap_data'][] = [
                                                        'rid' => $ogd['recode']['id'],
                                                        'rname' => $ogd['recode']['name'],
                                                        'gid' => $map_good['id'],
                                                        'gname' => $map_good['name'],
                                                        'or_price' => $map_good['or_prize'],
                                                        'now_price' => $map_good['now_prize'],
                                                    ];
                                                    $or_total_price += $map_good['or_prize'];
                                                }
                                            }
                                        }

                                        break;
                                    case $order['order_type'] == 7:
                                        $arr[$order['id']]['data'] = [];
                                        $arr[$order['id']]['order_name'] = '一生报告';
                                        $arr[$order['id']]['type'] = 5;
                                        foreach ($natal_report_goods as $natal_report_good)
                                        {
                                            foreach ($order_goods_datum as $ogd)
                                            {
                                                if ($ogd['gid'] == $natal_report_good['id'])
                                                {
                                                    $num += 1;
                                                    $arr[$order['id']]['data'][] = [
                                                        'gid' => (int)$natal_report_good['id'],
                                                        'title' => $natal_report_good['name'],
                                                        'rid' => $ogd['recode']['id'],
                                                        'rname' => $ogd['recode']['name'],
                                                        'or_price' => $natal_report_good['or_prize'],
                                                        'now_price' => $natal_report_good['now_prize'],
                                                    ];
                                                    $or_total_price += $natal_report_good['or_prize'];
                                                }
                                            }
                                        }
                                        break;
                                    case $order['order_type'] == 13:
                                        $arr[$order['id']]['data'] = [];
                                        $arr[$order['id']]['order_name'] = '一生报告';
                                        $arr[$order['id']]['type'] = 5;
                                        foreach ($sim_natal_report_goods as $natal_report_good)
                                        {
                                            foreach ($order_goods_datum as $ogd)
                                            {
                                                if ($ogd['gid'] == $natal_report_good['id'])
                                                {
                                                    $num += 1;
                                                    $arr[$order['id']]['data'][] = [
                                                        'gid' => (int)$natal_report_good['id'],
                                                        'title' => $natal_report_good['name'],
                                                        'rid' => $ogd['recode']['id'],
                                                        'rname' => $ogd['recode']['name'],
                                                        'or_price' => $natal_report_good['or_prize'],
                                                        'now_price' => $natal_report_good['now_prize'],
                                                    ];
                                                    $or_total_price += $natal_report_good['or_prize'];
                                                }
                                            }
                                        }
                                        break;
                                }
                            }
                        }
                        $arr[$order['id']]['count'] = $num;
                        $arr[$order['id']]['or_total_price'] = sprintf('%.2f', $or_total_price);
                        break;
                    case $videos && $order['order_type'] == 6:
                        $arr[$order['id']]['type'] = 4;
                        $arr[$order['id']]['order_name'] = '课程';
                        $num = 1;
                        $video_gid = 0;
                        $video_now_price = 0;
                        $video_or_price = 0;
                        foreach ($video_goods as $video_good)
                        {
                            if ($video_good['id'] == $order['gid'])
                            {
                                $video_now_price = $video_good['now_prize'];
                                $video_or_price = $video_good['or_prize'];
                                $video_gid = $video_good['id'];
                                $activeDiscount = active($video_good['id']);
                                if ($activeDiscount['discount'])
                                {
                                    $video_now_price *= $activeDiscount['discount'];
                                }
                            }
                        }
                        $video_id = 0;
                        $video_title = '';
                        $video_des = '';
                        foreach ($videos as $video)
                        {
                            if ($order['gid'] == $video['gid'])
                            {
                                $video_id = $video['id'];
                                $video_title = $video['title'];
                                $video_des = $video['description'];
                            }
                        }
                        $arr[$order['id']]['video_data'][] = [
                            'id' => (int)$video_id,
                            'gid' => (int)$video_gid,
                            'course_title' => $video_title,
                            'course_des' => $video_des,
                            'or_price' => $video_or_price,
                            'now_price' => $video_now_price
                        ];
                        $arr[$order['id']]['count'] = $num;
                        $arr[$order['id']]['or_total_price'] = sprintf('%.2f', $video_or_price * $num);
                        break;
                }

            }
        }
        return $arr;
    }

    /**
     * 获取购买订单的档案信息
     * @param $orders
     * @param $rids
     * @throws \Exception
     */
    public function OrderRecode($orders, $rids)
    {
        $rids = $rids ? array_values(array_unique($rids)) : [];
        $recodes = (new \app\common\cachemodel\Recode())->batchGetInfoByIds($rids, ['id', 'name', 'year', 'month', 'day']);
        foreach ($orders as $k => $order)
        {
            foreach ($recodes as $recode)
            {
                if ($recode['id'] == $order['rid'])
                {
                    $orders[$k]['recode'] = $recode;
                }
            }
        }

        return $orders;
    }
}
